package org.example.forkjoin;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.Future;

/**
 * 计算数组中所有元素的总和
 */
public class ForkJoinPoolExample {

    public static void main(String[] args) {
        int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};

        ForkJoinPool pool = new ForkJoinPool(); // 创建 ForkJoinPool 实例

        // invoke同步等待任务返回
        // execute：提交一个任务，不关心返回值
        //RecursiveSumTask task = new RecursiveSumTask(numbers, 0, numbers.length);
        //int result = pool.invoke(task); // 提交任务并等待结果

        Future<Integer> future = pool.submit(new RecursiveSumTask(numbers, 0, numbers.length));

        int result =0;
        try {
            result = future.get(); // 等待任务完成并获取结果
        } catch (Exception e) {
            e.printStackTrace();
        }

        System.out.println("The sum is: " + result);

        pool.shutdown(); // 关闭 ForkJoinPool
    }
}
